import Hls, {
  type HlsConfig, 
} from 'hls.js'

import CachedFragmentLoader from './CachedFragmentLoader'


export let hls: Hls | null = null

export const initHls = async (
  url: string,
  videoElement: HTMLVideoElement,
  setCurrentSegment: (segment: string) => void,
  setFullSegmentUrl: (url: string) => void,
  currentTime?: number
) => {
  if (hls) {
    hls.destroy()
  }

  const hlsConfig: Partial<HlsConfig> = {
    enableWorker: true,
    lowLatencyMode: true,
    fLoader: CachedFragmentLoader as any,
  }

  if (Hls.isSupported()) {
    hls = new Hls(hlsConfig)

    hls.attachMedia(videoElement)
    hls.loadSource(url)

    hls.on(Hls.Events.MANIFEST_PARSED, () => {
      videoElement.play()
      if (currentTime) {
        videoElement.currentTime = currentTime
      }
    })

    // 跟踪片段加载
    hls.on(Hls.Events.FRAG_LOADING, (_: any, data: any) => {
      // console.log('正在加载片段:', data);

      const {frag} = data
      
      if (frag.url) {
        setCurrentSegment(frag.relurl)
        setFullSegmentUrl(frag.url)
      }
    })

    hls.on(Hls.Events.ERROR, (_, data) => {
      if (data.fatal) {
        switch (data.type) {
          case Hls.ErrorTypes.NETWORK_ERROR:
            console.log('发生致命网络错误，尝试恢复...')
            hls?.startLoad()
            break
          case Hls.ErrorTypes.MEDIA_ERROR:
            console.log('发生致命媒体错误，尝试恢复...')
            hls?.recoverMediaError()
            break
          default:
            console.error('发生致命错误，无法恢复:', data)
            hls?.destroy()
            break
        }
      }
    })
  } else if (videoElement.canPlayType('application/vnd.apple.mpegurl')) {
    // 对于支持原生 HLS 的 Safari 浏览器
    videoElement.src = url
    videoElement.addEventListener('loadedmetadata', () => {
      videoElement.play()
      if (currentTime) {
        videoElement.currentTime = currentTime
      }
    })
  }
}